package cn.xiaoya.boot.jdbctemplate.util;

/**
 * @author xieya
 * @date 2021/7/27
 */
public final class IpUtil {
    public static long ip2Long(String ip) throws Exception {
        if (ip == null || ip.length() == 0) {
            return 0L;
        }
        String[] digits = ip.replaceAll(" ", "").split("\\.");
        long[] temp = null;
        boolean invalid = true;

        if (digits.length == 4) {
            temp = new long[]{Long.parseLong(digits[0]), Long.parseLong(digits[1]), Long.parseLong(digits[2]),
                    Long.parseLong(digits[3])};

            invalid = (temp[0] <= 0L) || (temp[0] > 255L) || (temp[1] < 0L) || (temp[1] > 255L) || (temp[2] < 0L)
                    || (temp[2] > 255L) || (temp[3] < 0L) || (temp[3] > 255L);
        }
        if (invalid) {
            throw new Exception("无效的IP地址 [" + ip + "].");
        }

        temp[0] <<= 24;
        temp[1] <<= 16;
        temp[2] <<= 8;

        return temp[0] | temp[1] | temp[2] | temp[3];
    }

    public static String long2Ip(long ip) {
        long a = ip % 256;
        long b = (ip -= a) >> 24;
        long c = (ip -= b << 24) >> 16;
        long d = ip - (c << 16) >> 8;
        return String.format("%d.%d.%d.%d", b, c, d, a);
    }

    private IpUtil() {
    }
}
